package com.msl.debezium.schedule;

import com.msl.debezium.common.DateUtil;
import com.msl.debezium.common.ReportUtil;
import com.msl.debezium.dto.DebeziumTestDto;
import com.msl.debezium.service.DebeziumTestService;
import com.msl.debezium.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class ValidationResportTask {

    private Logger logger = LoggerFactory.getLogger(ValidationResportTask.class);

    @Autowired
    private UserService userService;

    @Autowired
    private DebeziumTestService debeziumService;

    /**
     * 0 0 1 * * ?
     */
    @Scheduled(cron = "10 0/10 * * * ?")
    public void getReportTask(){

        Date date = new Date();
        logger.info("执行ValidationResportTask的getReportTask定时任务开始！");
        List<DebeziumTestDto> list = debeziumService.findAllByDate(date);
        if(list == null || list.size() == 0){
            logger.info("执行ValidationResportTask的getReportTask定时任务结束：前一天无测试数据");
            ReportUtil.createFile(DateUtil.dateTimeToStr(date)+"cdc-validation每日测试报告：前一天无表操作记录");
            return;
        }
        for (DebeziumTestDto debezium:list){
            String tableName = debezium.getTableName();
            Long countRead = debezium.getCountProcessed();
            Date createdAt = debezium.getCreatedAt();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());

            Date endDate = DateUtil.getDayBefore(new Date(),DateUtil.TIME_ZONE_SH,-1);
            Date startDate = DateUtil.getDayBefore(new Date(),DateUtil.TIME_ZONE_SH,0);

            StringBuffer sb = new StringBuffer();
            sb.append(DateUtil.dateTimeToStr(calendar.getTime()));
            sb.append(" cdc-validation每日测试报告：");
            sb.append(DateUtil.dateToStr(createdAt)).append("当天，表").append(tableName).append("写入");
            int countAdd = 0;
            try {
                countAdd = userService.countAddByTable(tableName, startDate, endDate);
                sb.append(countAdd);
            }catch (Exception e){
                sb.append("n(未知)").append(")");
            }
            sb.append(("条，读取")).append(countRead).append("条");

            logger.info(sb.toString());
            //写入日志文件
            ReportUtil.createFile(sb.toString());

        }
        logger.info("执行ValidationResportTask的getReportTask定时任务结束！");
    }

}
